# utils/decorators.py
from functools import wraps
from django.http import JsonResponse
from utils.response import ResponseUtil  # 引入统一响应工具类


def check_user_permission(user, permission_required):
    """
    校验用户权限，可以根据需求设计为数据库查询或其他逻辑。
    """
    if user.has_perm(permission_required):
        return True
    return False


def permission_required(permission):
    """
    装饰器：用于校验用户是否拥有指定权限
    """

    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            user = request.user  # 获取当前用户
            if not user.is_authenticated:
                return ResponseUtil.unauthorized(message="用户未登录")

            if not check_user_permission(user, permission):
                return ResponseUtil.unauthorized(message="无权限访问该接口")

            return view_func(request, *args, **kwargs)

        return _wrapped_view

    return decorator
